function likes(postID){
    var params = {'id': postID,
                  'v': 1  
                };
    
    makeAPICall('POST', 'notes', 'likes', params, function(response){
        var img = response.img;
        var likes = response.likes;
        var s = $('<img onClick="likes('+postID+')" src="'+img+'"/>');
        $('#likeimg'+postID).html(s);
        $('#likes'+postID).html(likes);
        return false;
    });
}

function flags(postID){
    var params = {'id': postID,
                  'v': 1  
                };
    
    makeAPICall('POST', 'notes', 'flags', params, function(response){
        var img = response;
        var s = $('<img onClick="flags('+postID+')" src="'+img+'"/>');
        $('#flagimg'+postID).html(s);
        return false;
    });
}

function CheckLength() {
    var msg_area = document.getElementById("error");
    msg_area.innerHTML = "";
    if (document.getElementById("query").value.length == 0) {
        document.getElementById("submit").submit();
    }
    else if(document.getElementById("query").value.length < 3){
        msg_area.innerHTML = "Please use at least 3 characters.";
    }
    else document.getElementById("submit").submit();
}

function CheckPost() {
    var msg_area = document.getElementById("error");
    msg_area.innerHTML = "";
    if (document.getElementById("message").value.length > 3) {
        if(document.getElementById("location").value == "Current Location")
        {
            getLocationforPost();
        }
        else
            document.getElementById("form").submit();
    }
    else {
        msg_area.innerHTML = "Message too short!";
    }
}

function CheckReply(postID) {
    var msg_area = document.getElementById("error");
    msg_area.innerHTML = "";
    var message = document.getElementById("reply").value;
    if (message.length > 3) {
        var params = {'id': postID,
                      'message': message,
                      'v': 1  
                     };
    
        makeAPICall('POST', 'notes', 'reply', params, function(){
            window.location = window.location.pathname+"?postID="+postID;
            return false;
        });
    }
    else {
        msg_area.innerHTML = "Message too short!";
    }
}

function AddMouseWheel(){
    $("body").mousewheel(function(event, delta){
        var scroll_value = delta * 50;
        if (jQuery.browser.webkit) {
            this.scrollLeft -= scroll_value;

        } else {
            document.documentElement.scrollLeft -= scroll_value;
        }
        return false;
    });
}

$(function(){
    AddMouseWheel();
})

var x=document.getElementById("demo");

function getLocation()
{
  if (navigator.geolocation)
    {
    navigator.geolocation.getCurrentPosition(showPosition,showError, {enableHighAccuracy: true});
    }
  else{x.innerHTML="Geolocation is not supported by this browser.";}
  
}

function getLocationforPost()
{
    if(navigator.geolocation){
        navigator.geolocation.getCurrentPosition(getPosition, showError, {enableHighAccuracy: true});
    }
    else {
        var msg_area = document.getElementById("error");
        msg_area.innerHTML = "Geolocation is not supported by this browser.";
    }
        
}

function getPosition(position)
{
    var theForm = document.getElementById("form");  
    var latoption = document.createElement('input'); 
    latoption.type = 'hidden';
    latoption.name = 'latitude';
    latoption.value = position.coords.latitude;
    theForm.appendChild(latoption);
    
    var lngoption = document.createElement('input'); 
    lngoption.type = 'hidden';
    lngoption.name = 'longitude';
    lngoption.value = position.coords.longitude;
    theForm.appendChild(lngoption);
    
    document.getElementById("form").submit();
}

function showPosition(position)
{
    lat=position.coords.latitude;
    lon=position.coords.longitude;
    latlon=new google.maps.LatLng(lat, lon)
    mapholder=document.getElementById('map_canvas')
    mapholder.style.width='300px';
    mapholder.style.height='400px';
    
    var myOptions=
    {
        center:latlon,
        zoom:16,
        mapTypeId:google.maps.MapTypeId.ROADMAP,
        mapTypeControl:false,
        navigationControlOptions:{style:google.maps.NavigationControlStyle.SMALL}
    };

    var map=new google.maps.Map(document.getElementById("map_canvas"),myOptions);
    var marker=new google.maps.Marker({position:latlon,map:map,title:"You are here!"});

    getMarkers(map);
}

function showLatLong()
{
    var lat = document.getElementById("lat").value;
    var lon = document.getElementById("lon").value;
    
    if(!isNumber(lat) || !isNumber(lon)) {
        window.alert("Enter numbers!");
        return;
    }
        
    latlon=new google.maps.LatLng(lat, lon);
    mapholder=document.getElementById('map_canvas');
    mapholder.style.width='300px';
    mapholder.style.height='400px';
    
    var myOptions=
    {
        center:latlon,
        zoom:16,
        mapTypeId:google.maps.MapTypeId.ROADMAP,
        mapTypeControl:false,
        navigationControlOptions:{style:google.maps.NavigationControlStyle.SMALL}
    };

    var map=new google.maps.Map(document.getElementById("map_canvas"),myOptions);
    var marker=new google.maps.Marker({position:latlon,map:map,title:"You are here!"});

    getMarkers(map);
}

function isNumber (o) {
  return ! isNaN (o-0) && o !== null && o !== "" && o !== false;
}

function showError(error)
{
  switch(error.code) 
    {
    case error.PERMISSION_DENIED:
      x.innerHTML="User denied the request for Geolocation."
      break;
    case error.POSITION_UNAVAILABLE:
      x.innerHTML="Location information is unavailable."
      break;
    case error.TIMEOUT:
      x.innerHTML="The request to get user location timed out."
      break;
    case error.UNKNOWN_ERROR:
      x.innerHTML="An unknown error occurred."
      break;
    }
}

function getMarkers(map)
{
    makeAPICall('POST', 'notes', 'addmarkers', {'v':1}, function(response){
        for ( i = 0; i < response.length; i++){
            var url = "popular?locID="+response[i].locID;
            var lat = response[i].lat;
            var lon = response[i].lon;
            var latlon = new google.maps.LatLng(lat, lon);
            createmarker(map, latlon, url)
        }
    });
}

function createmarker(map, latlon, url)
{
    var marker = new google.maps.Marker({
        position: latlon,
        map: map
    });
    google.maps.event.addListener(marker, 'click', function() {
        window.location.href = url;
    });
}

function currentposition()
{
    if(navigator.geolocation){
        navigator.geolocation.getCurrentPosition(indexPosition, showError, {enableHighAccuracy: true});
    }
    else {
        var msg_area = document.getElementById("position");
        msg_area.innerHTML = "Geolocation is not supported by this browser!";
    }
}

function indexPosition(position)
{
    lat1 = position.coords.latitude;
    lon1 = position.coords.longitude;
    var ubclat = 49.264052;
    var ubclon = -123.249435;
    var UBCradius = getdistance(ubclat,49.252849,ubclon,-123.249435);
    var mydistance = getdistance(lat1, ubclat, lon1, ubclon);
    var distances = new Array();
    makeAPICall('POST', 'notes', 'getlocations', {'v':1}, function(response){
        for ( i = 0; i < response.length; i++){
            var lat2 = response[i].lat;
            var lon2 = response[i].lon;
            var name = response[i].name;
            var distance = getdistance(lat1, lat2, lon1, lon2);
            var location = [name, distance];
            distances.push(location);
        }
        distances.sort(function(a,b){
            return a[1] - b[1];
        });
        var msg_area = document.getElementById("position");
        if(mydistance > UBCradius)
        {
            msg_area.innerHTML = "You are not <br> on Campus!";
        }
        else
            msg_area.innerHTML = "You are at <br>"+distances[0][0];   

    });
}

function getdistance(lat1, lat2, lon1, lon2)
{
    var R = 6371; // km
    var dLat = toRad(lat2-lat1);
    var dLon = toRad(lon2-lon1);
    lat1 = toRad(lat1);
    lat2 = toRad(lat2);

    var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
            Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2); 
    var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
    var d = R * c;
    return d;
}

function closeNotes() {

    if(navigator.geolocation){
        navigator.geolocation.getCurrentPosition(getNotes, showError, {enableHighAccuracy: true});
    }
    else {
        var msg_area = document.getElementById("error");
        msg_area.innerHTML = "Geolocation is not supported by this browser!";
    }
}

function getNotes(position)
{
    mylat = position.coords.latitude;
    mylon = position.coords.longitude;

    var locations = new Array();
    makeAPICall('POST', 'notes', 'getAllLocations', {'v':1}, function(response){
        for ( i = 0; i < response.length; i++){
            var lat2 = response[i].lat;
            var lon2 = response[i].lon;
            var locID = response[i].locID;
            var distance = getdistance(mylat, lat2, mylon, lon2);
            if(distance < 0.1)
                locations.push(locID);
        }
        var theForm = document.getElementById("submit");  

        var nearby = document.createElement('input'); 
        nearby.type = 'hidden';
        nearby.name = 'nearby';
        nearby.value = 1;
        theForm.appendChild(nearby);

        for(i = 0; i < locations.length; i++)
        {       
            var location = document.createElement('input'); 
            location.type = 'hidden';
            location.name = 'locations[]';
            location.value = locations[i];
            theForm.appendChild(location);
        }
        document.getElementById("submit").submit();  
    });   
}

function toRad(Value) {
    /** Converts numeric degrees to radians */
    return Value * Math.PI / 180;
}